import axios, { AxiosRequestConfig, AxiosResponse } from "axios";

// 设置默认的请求配置
// axios.defaults.baseURL = "http://192.168.150.165:8080"; // 设置接口基础地址
// axios.defaults.baseURL = "https://www.step2step.cn"; // 设置接口基础地址
// http://192.168.150.66:8080/api/v1/user/register

// 创建 Axios 实例
const api = axios.create({
    timeout: 5000
});

// 请求拦截器
api.interceptors.request.use(
    (config: any) => {
        // 从本地存储或其他地方获取 token，并设置到请求头
        const token = localStorage.getItem("token");
        if (token && !config.url?.includes("/login")) {
            config.headers!["Authorization"] = `Bearer ${token}`;
        }

        return config;
    },
    error => {
        // 处理请求错误
        return Promise.reject(error);
    }
);

// GET 方法封装
export const get = <T>(url: string, params?: any): Promise<T> => {
    return new Promise<T>(resolve => {
        api.get(url, { params })
            .then((response: AxiosResponse<any>) => {
                resolve(response.data);
            })
            .catch(error => {
                console.error(error);
                resolve(null as any);
            });
    });
};

// delete 方法封装
export const remove = <T>(url: string, params?: any): Promise<T> => {
    return new Promise<T>(resolve => {
        api.delete(url, { params })
            .then((response: AxiosResponse<any>) => {
                resolve(response.data);
            })
            .catch(error => {
                console.error(error);
                resolve(null as any);
            });
    });
};

// Patch 方法封装
export const patch = <T>(url: string, data?: any, isJson = false): Promise<T> => {
    let param = data;
    const headers: any = {};
    if (!isJson) {
        const formdata = new FormData();
        for (let i in data) {
            formdata.append(i, data[i]);
        }
        param = formdata;
        headers["Content-Type"] = "application/x-www-form-urlencoded";
    }
    return new Promise<T>(resolve => {
        api.patch(url, param, {
            headers
        })
            .then((response: AxiosResponse<any>) => {
                resolve(response.data);
            })
            .catch(error => {
                console.error("網絡錯誤", error);
                resolve(null as any);
            });
    });
};

// POST 方法封装
export const post = <T>(url: string, data?: any, isJson = false): Promise<T> => {
    let param = data;
    const headers: any = {};
    if (!isJson) {
        const formdata = new FormData();
        for (let i in data) {
            formdata.append(i, data[i]);
        }
        param = formdata;
        headers["Content-Type"] = "application/x-www-form-urlencoded";
    }
    return new Promise<T>(resolve => {
        api.post(url, param, {
            headers
        })
            .then((response: AxiosResponse<any>) => {
                resolve(response.data);
            })
            .catch(error => {
                console.error("網絡錯誤", error);
                resolve(null as any);
            });
    });
};
